/*
 * GYAsyncCmd.cpp
 *
 *  Created on: 2015-10-11
 *      Author: gy
 */


#include "GYAsyncCmd.h"
#include "GYAsyncCmdFactory.h"

GYAsyncCmd::GYAsyncCmd():m_pstParent(NULL),m_pstChild(NULL),
			m_iCmdId(0),m_iCmdSeq(0)
{

}

GYAsyncCmd::~GYAsyncCmd()
{
	if (m_pstChild != NULL && m_pstChild->m_pstParent == this)
	{
		m_pstChild->m_pstParent = NULL;
	}

	if (m_pstParent != NULL && m_pstParent->m_pstChild == this)
	{
		m_pstParent->m_pstChild = NULL;
	}

	m_bParentEnableLogicDo = false;
}

/**
* 在调用子命令Do之前先RegChild
*/
void GYAsyncCmd::RegisterChild(GYAsyncCmd* pstChild, bool bParentEnableLogicDo)
{
	if (pstChild)
	{
		this->m_pstChild = pstChild;
		pstChild->m_pstParent = pstChild;
		pstChild->m_bParentEnableLogicDo = bParentEnableLogicDo;
		Retain();
	}
}

/**
* 生成命令后执行Do函数.
* @param[in] pData 用void*做参数, 以不变应万变
*/
int GYAsyncCmd::Do(void* pData)
{
	return 0;
}

/**
* 默认回调函数是执行Done
*/
int GYAsyncCmd::CallBack(int iRet)
{
    return Done(iRet);
}

/**
* 如果没有子命令, 外部收到响应后调用命令的OnAnswer函数
* @param[in] pData 用void*做参数, 以不变应万变
*/
int GYAsyncCmd::OnAnswer(void* pData)
{
    return 0;
}

/**
* 默认调用callback
*/
int GYAsyncCmd::LogicDo(int iRet)
{
    return CallBack(iRet);
}

/**
* 命令执行完毕后调用Done函数, 以便自动释放或回调父命令
*/
int GYAsyncCmd::Done(int iRet)
{
	if (m_pstParent)
	{
		if (m_bParentEnableLogicDo)
		{
			m_pstParent->LogicDo(iRet);
		}
		else
		{
			m_pstParent->CallBack(iRet);
		}
		m_pstParent->Release();
	}

	m_pstParent = NULL;
	m_bParentEnableLogicDo = false;
	GY_CMDFACTORY->FreeCmd(this);

	return iRet;
}
